package com.ctfo.ulcp.exp.server

import io.vertx.core.json.Json
import io.vertx.ext.web.Router
import io.vertx.ext.web.handler.BodyHandler
import io.vertx.jdbcclient.JDBCPool
import io.vertx.kotlin.coroutines.CoroutineVerticle
import org.slf4j.LoggerFactory

class CodeExecServer : CoroutineVerticle() {

    data class Response(val code: Int = 0, val msg: String = "成功", var data: Any?)

    private val logger = LoggerFactory.getLogger("CodeExecServer")
    private lateinit var pool: JDBCPool

    override suspend fun start() {
        val httpServer = vertx.createHttpServer()
        val router = Router.router(vertx)


        httpServer.requestHandler(router).listen(5000).onComplete { ar ->
            if (ar.failed()) {
                logger.error("code exec server start failed")
                ar.cause().printStackTrace()
                vertx.close()
            }
        }
        router.post().handler(BodyHandler.create())

        router.post("/exec/sql").handler { ctx ->
            val param = ctx.bodyAsJson
            logger.info("request: core/sql-exec, param:{}", param)
            val data = listOf(
                mapOf("id" to "1", "email" to "test@abc.com"),
                mapOf("id" to "2", "email" to "chengyi@abc.com"),
            )

            ctx.json(Response(data = data))
        }

        router.post("/exec/api").handler { ctx ->
            val param = ctx.bodyAsJson
            logger.info("request: core/interface-exec, param:{}", param)

            val str = param.getString("queryContent")
            println("调用远程接口: ${Json.decodeValue(str)}")
            ctx.json(Response(data = "邮件发送成功"))
        }

    }


}